package com.zong.ai.agent.advisor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.dfa.SensitiveUtil;
import org.springframework.ai.chat.client.advisor.api.*;
import reactor.core.publisher.Flux;

import java.util.Set;

/**
 * @author: zongzi
 * @description: 基于hutool工具包实现的 违禁词 advisor
 * @date: 2025/6/17
 */
public class SensitiveWordAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {
    private Set<String> bannedWords;

    public SensitiveWordAdvisor(String... bannedWords) {
        this.bannedWords = CollUtil.newHashSet(bannedWords);
    }

    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        String userMessage = advisedRequest.userText();
        SensitiveUtil.init(bannedWords);
        boolean hasForbidden = SensitiveUtil.containsSensitive(userMessage);
        if (hasForbidden) {
            throw new RuntimeException("用户输入包含违禁词！");
        }
        return chain.nextAroundCall(advisedRequest);
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        String userMessage = advisedRequest.userText();
        SensitiveUtil.init(bannedWords);
        boolean hasForbidden = SensitiveUtil.containsSensitive(userMessage);
        if (hasForbidden) {
            throw new RuntimeException("用户输入包含违禁词！");
        }

        return chain.nextAroundStream(advisedRequest);
    }

    @Override
    public String getName() {
        return this.getClass().getName();
    }

    @Override
    public int getOrder() {
        return -10;
    }
}
